#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "huffman.h"
#include "bf.h"

int main (int argc, char *argv[]) {
  int c;
  FILE *in;
  bf_stream out;
  struct huff_code_struct cs;
  
  if (argc != 3) {
    fprintf (stderr, "usage : %s <infile> <outfile>\n", argv[0]);
    exit (EXIT_FAILURE);
  }

  if (!strncmp (argv[1], "-", 2)) {
    in = stdin;
  } else if (!(in = fopen (argv[1], "r"))) {
    perror ("compress : error opening input file");
    exit (EXIT_FAILURE);
  }

  if (!strncmp (argv[2], "-", 2)) {
    if (!(out = bf_stream_new (1))) {
    perror ("compress : error opening output file");
    exit (EXIT_FAILURE);
    }
  } else if (!(out = bf_open (argv[2], BF_WRITE))) {
    perror ("compress : error opening output file");
    exit (EXIT_FAILURE);
  }

  c = fgetc (in);
  huff_tree_init (c);
  bf_putchar (out, c);

  while ((c = fgetc (in)) != EOF) {
    if (huff_getcode (c, &cs)) {
      huff_putcode (out, &cs);
    } else {
      huff_special_code (&cs);
      huff_putcode (out, &cs);
      bf_putchar (out, c);
    }
    huff_tree_modify (c);
  }

  if (!bf_isaligned (out)) {
    huff_special_code (&cs);
    huff_putcode (out, &cs);
    bf_align (out);
  }
  bf_close (out);
  fclose (in);

  return (EXIT_SUCCESS);
}
